using anydata.Entitys;
using Newtonsoft.Json.Linq;
using System.Collections;
using System.Text.RegularExpressions;
using Jint;
using Newtonsoft.Json;

namespace anydata.Services
{
    public class RuleService : ITransient
    {
        public void Converting(IEnumerable datas, XForm? form)
        {
            foreach (EntityBase data in datas)
            {
                foreach (var field in form.fields)
                {
                    var queryRule = field.queryRule;
                    if (string.IsNullOrEmpty(queryRule)) continue;

                    var rule = JsonConvert.DeserializeObject<Dictionary<string, object>>(queryRule);
                    if (rule?["formula"] is not string formula || rule["mappingData"] is not JArray mappingData)
                    {
                        continue;
                    }

                    if (mappingData.Count > 0)
                    {
                        var codes = mappingData.Select(item => item["code"]?.ToString())
                            .Where(code => !string.IsNullOrEmpty(code)).ToList();
                        formula = ReplaceCodesInFormula(data, codes, formula);
                    }

                    data[field.attr] = new Engine().SetValue("data", data).Evaluate(formula).ToObject();
                }
            }
        }

        private string ReplaceCodesInFormula(EntityBase data, List<string> codes, string formula)
        {
            foreach (var code in codes)
            {
                formula = Regex.Replace(formula, $@"\b{Regex.Escape(code)}\b", data[code]?.ToString() ?? string.Empty);
            }

            return formula;
        }
    }
}